/**
 * 限制excel类型的上传文件框
 * @author: tongsitong
 */

import styles from "./index.less";
import IconUploadRed from "@/assets/icons/icon-upload-red.png";
import { Button, message, Upload } from "antd";
import { getAuthority } from "@/utils/authority";
import { forwardRef, useImperativeHandle, useState } from "react";
import xls_img from "@/assets/icons/icon-upload-xls.png";
import csv_img from "@/assets/icons/icon_upload_undefined.png";
import {fof_portfolio_data} from './data'; // mock data
interface uploadFileProps {
  accept?: string; // 接受的文件如.xlsx,.csv
  action?: string; // 上传接口，如/api/fund/fund_portfolio/report/excel_import
  setFile: any;
  setResData?: any; // 上传文件后返回的data
  style?: any;
  maxCount?: Number; // 最多同时上传文件数
  isError?: boolean; // 没上传是否出现红色框
}

export const UploadFile = forwardRef((props: uploadFileProps, ref: any) => {
  const [localFile, setLocalFile] = useState({});
  const { setResData, setFile, maxCount, accept, action, style, isError } = props;
  useImperativeHandle(ref, ()=>({
    handleClearFile
  }));
  
  // 清空文件内容
  const handleClearFile = ()=>{
    setLocalFile({});
  }
  const uploadProps = {
    accept: accept || ".xlsx,.csv",
    action: action || "/api/fund/portfolio/upload/fof_portfolio",
    showUploadList: false,
    headers: {
      token: getAuthority("dh-authority")?.accessToken, //设置上传的请求头部
    },
    maxCount: maxCount || 1,
    onChange({ file, fileList }) {
      console.log(file, fileList);
      if (file.status === "done") {
        file.ext = file.name.split(".").pop();
        setFile(file);
        setLocalFile(file);
        if (process.env.REACT_APP_ENV === "mock") {
          setResData(fof_portfolio_data);
        } else {
          let res = file?.response;
          // 报错统一外部报
          setResData(res);
        }
      }
    },
  };
  return (
    <div className={[isError? styles.red_wrapper : null ,styles.upload_comp_wrapper].join(' ')} style={style}>
      <Upload className={styles.upload_comp} {...uploadProps}>
        <span className={styles.before_upload}>
          {localFile.name ? (
            <div>
              <img
                src={
                  localFile.ext === "xlsx" || localFile.ext === "xls"
                    ? xls_img
                    : csv_img
                }
              />
              {localFile.name}
            </div>
          ) : (
            <span className={styles.placeholder}>请上传 EXCEL或CSV</span>
          )}
        </span>
        <Button
          className={styles.upload_btn}
          icon={<img src={IconUploadRed} />}
        ></Button>
      </Upload>
    </div>
  );
});
